﻿using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using AvalonEdit.Sample;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Highlighting;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;

namespace Poet
{
    public partial class ChildWindow
    {
        public static RoutedCommand GoTo = new RoutedCommand("GoTo", typeof(ChildWindow));
        public static RoutedCommand PageSetup = new RoutedCommand("PageSetup", typeof(ChildWindow));
        public static RoutedCommand Font = new RoutedCommand("DefaultFont", typeof(ChildWindow));

        public static Font DefaultFont { get; set; }

        FoldingManager _foldingManager;
        AbstractFoldingStrategy _foldingStrategy;

        static ChildWindow()
        {
            DefaultFont = new Font("Segoe UI", 14);
        }

        readonly Timer _timer = new Timer{Interval = 10, Enabled = false};
        
        public  void SetFocus()
        {
            _timer.Enabled = true;
        }

        public void Tick(object o, EventArgs e)
        {
            _textEditor.Focus();
            if (_timer.Enabled) _timer.Enabled = false;
        }


        public ChildWindow()
        {
            InitializeComponent();
            DefaultElement = _textEditor.TextArea;

            _textEditor.FontFamily = new System.Windows.Media.FontFamily(DefaultFont.FontFamily.Name);
            _textEditor.FontSize = DefaultFont.Size;
       
        }

        public static ChildWindow CreateNew(string name)
        {
            return new ChildWindow {Title = name};
        }

        public string FileName { get; set; }

        public ChildWindow(string filePath)
        {
            FileName = filePath;
            _timer.Tick += Tick;
            InitializeComponent();
            DefaultElement = _textEditor.TextArea;
            _textEditor.FontFamily = new System.Windows.Media.FontFamily(DefaultFont.FontFamily.Name);
            _textEditor.FontSize = DefaultFont.Size;
            Title = Path.GetFileName(filePath);

            try
            {
                //var text = new CodeColorizer().Colorize(File.ReadAllText(fileName, Encoding.GetEncoding(1251)), Languages.CSharp);
                //textBox.Document.Blocks.Add(new Paragraph(new Run(text)));
                if (new FileInfo(filePath).Length > 500)
                    _textEditor.Options.ShowBoxForControlCharacters = false;

                _textEditor.Load(filePath);
                _textEditor.SyntaxHighlighting = HighlightingManager.Instance.
                    GetDefinitionByExtension(Path.GetExtension(filePath));

                HighlightingComboBoxSelectionChanged(null, null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool _folding;
        public bool Folding
        {
            get
            {
                return _folding;
            }
            set
            {
                _folding = value;
                if (!value)
                {
                    if (_foldingManager != null) FoldingManager.Uninstall(_foldingManager);
                }
                else
                {
                    _foldingManager = FoldingManager.Install(_textEditor.TextArea);
                    HighlightingComboBoxSelectionChanged(null, null);
                }
            }
        }

        public void HighlightingComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!Folding) return;

            if (_textEditor.SyntaxHighlighting == null)
            {
                _foldingStrategy = null;
            }
            else
            {
                switch (_textEditor.SyntaxHighlighting.Name)
                {
                    case "XML":
                        _foldingStrategy = new XmlFoldingStrategy();
                        _textEditor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy();
                        break;
                    case "C#":
                    case "C++":
                    case "PHP":
                    case "Java":
                        _textEditor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options);
                        _foldingStrategy = new BraceFoldingStrategy();
                        break;
                    default:
                        _textEditor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy();
                        _foldingStrategy = null;
                        break;
                }
            }
            if (_foldingStrategy != null)
            {
                if (_foldingManager == null)
                    _foldingManager = FoldingManager.Install(_textEditor.TextArea);
                _foldingStrategy.UpdateFoldings(_foldingManager, _textEditor.Document);
            }
            else
            {
                if (_foldingManager != null)
                {
                    FoldingManager.Uninstall(_foldingManager);
                    _foldingManager = null;
                }
            }
        }

        private double _scale = 1;

        private void TextEditorPreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            try
            {
                if (Keyboard.Modifiers == ModifierKeys.Control)
                {
                    _scale += (double)e.Delta / 1000;
                    _textEditor.FontSize = DefaultFont.Size*_scale;
                    //_textEditor.TextArea.RenderTransform = new ScaleTransform(scale, scale, Mouse.GetPosition(_textEditor).X, Mouse.GetPosition(_textEditor).Y);
                    
                    e.Handled = true;
                }
            }
            catch
            { }
        }

        public void Save_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (FileName != null) _textEditor.Save(FileName);
            else SaveAs_Executed(sender, e);
            DefaultElement.Focus();
        }

        public void SaveAs_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var saveFileDialog = new SaveFileDialog
                                     {
                                         Filter = @"Text files (*.txt, *.xml)|*.txt;*.xml|All files (*.*)|*.*",
                                         FileName = Title
                                     };
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                FileName = saveFileDialog.FileName;
                Title = Path.GetFileName(FileName);
            }
            else
            {
                DefaultElement.Focus();
                return;
            }

            _textEditor.Save(FileName);
            DefaultElement.Focus();
        }

        private void Close_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Close();
        }

        private void DocumentContent_PreviewDragOver(object sender, System.Windows.DragEventArgs e)
        {
            Activate();
        }

        private void GoTo_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var currentLineNumber =
                _textEditor.Document.GetLineByOffset(_textEditor.CaretOffset).LineNumber;
            var dialog = new GoToLineDialog(1, _textEditor.LineCount, currentLineNumber)
                             {
                                 Owner = Application.Current.MainWindow,
                             };
            if (dialog.ShowDialog() != true) return;

            _textEditor.TextArea.Caret.Line = dialog.LineNumber;
            _textEditor.ScrollTo(
                _textEditor.TextArea.Caret.Line,
                _textEditor.TextArea.Caret.Column);
        }

        private void Grid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Activate();
        }

        private void PrintPreviewOnExecute(object sender, ExecutedRoutedEventArgs e)
        {
            //var fd = new FlowDocument(new Paragraph(new Run(_textEditor.Text)));

            var d = new FixedDocument();
            //var pageContent = new PageContent();
            
            //d.Pages.Add(_textEditor.Text);

            var p = new PrintPreviewWindow();
            p._documentViewer.Document = d;
            p.ShowDialog();

            /*
            PrintDocument document = new PrintDocument();
            document.DocumentName = strLoadedFile;

            PrintPreviewDialog dlg = new PrintPreviewDialog();
            dlg.Document = document;
            dlg.UseAntiAlias = true;// Включить сглаживание

            dlg.ShowDialog();
            //txtBox1.Focus();
             * */
        }

        private void PrintOnExecute(object sender, ExecutedRoutedEventArgs e)
        {
            var flowDocument = new FlowDocument(new Paragraph(new Run(_textEditor.Text)));
                //new FlowDocument {DataContext = _textEditor.Text};

            var printDialog = new System.Windows.Controls.PrintDialog();      
            if(printDialog.ShowDialog() != true) return;

            var panginateDocument = ((IDocumentPaginatorSource) flowDocument).DocumentPaginator;
            printDialog.PrintDocument(panginateDocument, Name);

        }

        private void PageSetupExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var psd = new PageSetupDialog {PageSettings = new PageSettings()};
            psd.ShowDialog();
            /*
            var document = new PrintDocument {DocumentName = Name};
            var printPreviewDialog = new PrintPreviewDialog {Document = document};
            printPreviewDialog.ShowDialog();
             * */
        }

        private void DocumentContent_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //e.Handled = true;
        }

        private void FontExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var fontDialog = new FontDialog
                                 {
                                     Font = new Font(_textEditor.FontFamily.ToString(), (float) _textEditor.FontSize)
                                 };
            if (fontDialog.ShowDialog() != DialogResult.OK)
            {
                _textEditor.Focus();
                return;
            }
            DefaultFont = fontDialog.Font;
            _textEditor.FontFamily = new System.Windows.Media.FontFamily(DefaultFont.FontFamily.Name);
            _textEditor.FontSize = DefaultFont.Size;
            _textEditor.Focus();
        }
    }
}
